package jmine.tec.publisher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import jmine.tec.subscription.SubscriptionSettings;
import jmine.tec.subscription.impl.AbstractPublisher;
import jmine.tec.subscription.impl.PartialPublication;
import jmine.tec.subscription.impl.PlainSubscriptionSettings;

import org.springframework.beans.factory.InitializingBean;

public class SimplePublisher extends AbstractPublisher<SimplePublication> implements InitializingBean {

    private Thread thread = new Thread() {
        @Override
        public void run() {
            final PlainSubscriptionSettings settings = new PlainSubscriptionSettings(new HashMap<String, Object>());
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    SimplePublisher.this.publish(settings, new SimplePublication(line));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    };

    public void publishNewEvent(String event) {
        final PlainSubscriptionSettings settings = new PlainSubscriptionSettings(new HashMap<String, Object>());
        this.publish(settings, new SimplePublication(event));
    }

    public void publishPartial() {
        final PlainSubscriptionSettings settings = new PlainSubscriptionSettings(new HashMap<String, Object>());
        publishPartialPublication(settings, new PartialPublication<SimplePublication>() {
            
            private static final long serialVersionUID = -8194315491956685890L;

            public SimplePublication merge(SimplePublication original) {
                return new SimplePublication(original.getText() + "#");
            }
        });
    }
    
    public SimplePublisher() {
        super(SimplePublication.class);
        this.thread.setDaemon(true);
    }

    @Override
    public void evict(SubscriptionSettings settings) {
    }

    public String identification() {
        return "simplePublisher";
    }

    public SimplePublication newPublication(SubscriptionSettings settings) {
        return new SimplePublication(settings.toString());
    }

    public void afterPropertiesSet() throws Exception {
        this.thread.start();
    }

    public Map<String, Class<?>> subscriptionSettingsParameters() {
        return new HashMap<String, Class<?>>();
    }

}
